<template>
  <div class="login-container">
    <van-nav-bar
      class="page-nav-bar"
      title="登录"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="logo-txt">
      欢迎登录
    </div>
    <van-form @submit="onSubmit" class="login-form">
      <van-field
        class="logininput"
        v-model="user.username"
        name="username"
        placeholder="请输入账户名"
        :rules="rules.username"
        left-icon="manager-o"
        label="账户名"
        clearable
      />
      <van-field
        class="logininput"
        v-model="user.password"
        type="password"
        name="password"
         label="密码"
          left-icon="lock"
        placeholder="请输入密码"
        clearable
        :rules="rules.password"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit" >立即登录
        </van-button>
      </div>
    </van-form>
    <van-row class="help" type="flex" justify="space-between">
      <van-col span="6"  @click='$router.push("/register")'>前往注册</van-col>
      <van-col span="6" @click='$router.push("/reset")'>忘记密码</van-col>
    </van-row>
  </div>
</template>

<script>
import { login } from "@/api/user";
export default {
  data() {
    return {
      user: {
        username: '醉酒笑红尘',
        password: "admin888",
      },
      rules: {
        username: [
          {
            required: true,
            message: "账号不能为空",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
          },
        ],
      },
    };
  },
  methods: {
    async onSubmit() {
      const user = this.user;
      this.$toast.loading({
        duration: 0,
        forbidClick: true,
        message: "登录中...",
      });
      try {
        const data = await login(user);
        this.$store.commit("user/setToken", data);
        this.$toast.success("登录成功,即将跳转到原先页面");
        setTimeout(() => {
          this.$router.replace(this.$route.query.redirect || '/my');
        }, 2000);
      } catch (error) {
         this.$toast.fail(error);
      }
    },
  },
};
</script>
<style lang="less" scoped>
.logo-txt {
  text-align: center;
  margin: 80px;
}
.help {
  color: #aaa;
  font-size: 30px;
  padding:  0 20px;
}
</style>